package com.hackcloud.shardingjdbc.config;

import com.hackcloud.shardingjdbc.dao.center.SimpleJpaNoCountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = {"com.hackcloud.shardingjdbc.dao.center"}, basePackageClasses = SimpleJpaNoCountRepository.class,
        entityManagerFactoryRef = "shardingManagerFactoryBean",
        transactionManagerRef = "shardingTransactionManager")
public class ShardingDataSourceConfig {


    @Autowired
    @Qualifier("dataSource")
    private DataSource writeDruidDataSource;


    @Bean(name = "shardingManagerFactoryBean")
    public LocalContainerEntityManagerFactoryBean shardingManagerFactoryBean(EntityManagerFactoryBuilder builder) {
        final LocalContainerEntityManagerFactoryBean defaultPersistenceUnit = builder
                .dataSource(writeDruidDataSource)
                .packages("com.hackcloud.shardingjdbc.domain.center") //设置实体类所在位置
                .persistenceUnit("shardingPersistenceUnit")
                .build();
        defaultPersistenceUnit.setPersistenceUnitPostProcessors(pui -> pui.addProperty("hibernate.physical_naming_strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy"));
        return defaultPersistenceUnit;
    }

    @Bean(name = "shardingEntityManager")
    public EntityManager shardingEntityManager(EntityManagerFactoryBuilder builder) {
        return shardingManagerFactoryBean(builder).getObject().createEntityManager();
    }

    /**
     * 配置事物管理器
     *
     * @return
     */
    @Bean(name = "shardingTransactionManager")
    public PlatformTransactionManager shardingTransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(shardingManagerFactoryBean(builder).getObject());
    }
}
